package com.taobao.machinesystem.service.impl;

import com.taobao.machinesystem.entity.SysPermission;
import com.taobao.machinesystem.entity.SysRolePermission;
import com.taobao.machinesystem.mapper.SysPermissionMapper;
import com.taobao.machinesystem.mapper.SysRolePermissionMapper;
import com.taobao.machinesystem.service.SysRolePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 角色权限 服务实现类
 * </p>
 *
 * @author LiuJunCheng
 * @since 2022-04-22
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements SysRolePermissionService {
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    /**
     * 赋予权限
     * @param ids
     * @return
     */
    @Override
    public void addRolePermission(String ids,String roleId) {
        Set<SysPermission> sysPermissions = new HashSet<>();
        //首先，根据传来的id分割为数据
        String[] split = ids.split(",");
        //查询出权限
        for (String s : split) {
            SysPermission sysPermission = this.sysPermissionMapper.selectById(s);
            sysPermissions.add(sysPermission);
            //根据id查询出父权限
            SysPermission permission = this.sysPermissionMapper.selectByPid(s);
            if (permission!=null && !"".equals(permission.getId())){
                boolean is = true;
                for (SysPermission sp : sysPermissions) {
                    if (permission.getId().equals(sp.getId())){
                        is = false;
                        break;
                    }
                }
                if (is) {
                    sysPermissions.add(permission);
                }
            }
        }
        //先把原有的权限给删除了
        System.out.println(roleId);
        int i = baseMapper.delRoleId(roleId);
        //添加个默认的进去
        SysRolePermission srp = new SysRolePermission();
        srp.setRoleId(roleId);
        srp.setPermissionId("1");
        baseMapper.insert(srp);
        //挨个添加进去
        for (SysPermission sysPermission : sysPermissions) {
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setRoleId(roleId);
            sysRolePermission.setPermissionId(sysPermission.getId());
            baseMapper.insert(sysRolePermission);
        }
    }
}
